package com.diorsunion.hedge.bo.db;

import com.diorsunion.hedge.util.CalendarUtils;
import com.diorsunion.hedge.common.Period;
import com.diorsunion.hedge.dal.entity.Stock;
import com.diorsunion.hedge.dal.entity.StockPrice;
import com.diorsunion.hedge.dal.repository.StockPriceRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by dingshanyyj on 15/12/24.
 */
@Service
public class StockPriceBO {

    @Resource
    protected StockPriceRepository stockPriceRepository;

    //    @Resource
//    protected StockRepository stockRepository;
    public void insert(Stock stock, StockPrice stockPrice, Period period) {
        stockPrice.stock = stock;
        /**咱不讲快,反正是个定时任务,咱讲正确率,
         还是先查一遍,有的话先删除,没有再增加**/
        List<StockPrice> stockPriceList_exist = stockPriceRepository.find(stockPrice, period);
        if (stockPriceList_exist != null && !stockPriceList_exist.isEmpty()) {
            stockPriceList_exist.forEach(stockPrice_delete -> stockPriceRepository.delete(stockPrice_delete.id, period));
        }
        /*然后找上一条数据的thedate,设置成本条数据的preDate*/
        Date yestoday = CalendarUtils.addDate(stockPrice.thedate, -1);
        Date last_Date = stockPriceRepository.getMaxDate(stock, yestoday, period);
        StockPrice last_stockPrice_query = new StockPrice();
        last_stockPrice_query.stock = stock;
        last_stockPrice_query.thedate = last_Date;

        List<StockPrice> stockPrices = stockPriceRepository.find(last_stockPrice_query, period);
        stockPrices.stream().forEach(x -> {
            x.nextDate = stockPrice.thedate;
            x.stock = stock;
            stockPriceRepository.update(x, period);
        });
        stockPrice.preDate = last_Date;
        stockPriceRepository.insert(stockPrice, period);
        /*同时要修改上一条数据的nextDate*/
    }
}
